package com.common.app.base

import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Process
import android.text.TextUtils
import android.util.Log
import androidx.viewbinding.ViewBinding
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.callback.NavCallback
import com.common.app.R
import com.common.app.core.RouterHub
import com.common.app.dialog.CommonDialog
import com.common.app.helper.RouterHelper
import com.common.app.helper.UserHelper
import com.common.app.utls.MD5Utils
import com.common.base.app.activity.BaseVMActivity
import com.common.base.app.viewmodel.BaseViewModel
import com.common.base.security.Base64Utils
import com.common.base.utils.AppMarketUtils
import com.common.base.utils.ToastUtils

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/8/19
 * <p>
 * 描述：中间层
 * <p>
 * 修订历史：
 */
abstract class AppActivity<VB : ViewBinding, VM : BaseViewModel> : BaseVMActivity<VB, VM>() {

    //密码已修改弹窗提示
    private var passwordAlterDialog: CommonDialog? = null


    var mValidate: String? = ""

    override fun initEvents() {
        super.initEvents()
    }

    /**
     * 易盾验证 成功回调
     */
    open fun onValidateSuccess() {}

    /**
     * 获取易盾验证
     */
//    open fun getCaptchaValidate() {
//    }

    /***
     * 打开应用市场
     * @param mContext
     * @param marketPackageName
     */
    open fun openMarket(mContext: Context, marketPackageName: String?) {
        try {
            AppMarketUtils.gotoMarket(this)
        } catch (anf: ActivityNotFoundException) {
            Log.e("MarketUtils", "要跳转的应用市场不存在!")
            openGoogleMarket(mContext, marketPackageName)
        } catch (e: Exception) {
            Log.e("MarketUtils", "其他错误：" + e.message)
        }
    }

    /***
     * 打开应用市场
     * @param mContext
     * @param marketPackageName
     */
    private fun openGoogleMarket(mContext: Context, marketPackageName: String?) {
        try {
            //谷歌商店
            val i = Intent(Intent.ACTION_VIEW)
            i.data = Uri.parse("https://play.google.com/store/apps/details?id=$marketPackageName")
            startActivity(i)
        } catch (anf: ActivityNotFoundException) {
            Log.e("MarketUtils", "要跳转的应用市场不存在!")
        } catch (e: Exception) {
            Log.e("MarketUtils", "其他错误：" + e.message)
        }
    }


    /**
     * 重启应用
     */
    fun restart() {
        try {
            Thread.sleep(1000)
        } catch (e: InterruptedException) {
            Log.e(TAG, "error : $e")
        }
        val intent = packageName?.let {
            packageManager?.getLaunchIntentForPackage(it)
        }
        intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        startActivity(intent)
        Process.killProcess(Process.myPid())
    }

    open fun toAcByAction(acName: String?) {
        if (TextUtils.isEmpty(acName)) {

            RouterHelper.navigation(RouterHub.ROUTER_BE_OPENED_ACTIVITY)
            return
        }
        try {
            // 使用别名名字的action
            val intent = Intent()
            intent.action = acName
           startActivity(intent)
        } catch (e: Exception) {
//            PToastUtils.t("抱歉、找不到该页面！");
            RouterHelper.navigation(RouterHub.ROUTER_BE_OPENED_ACTIVITY)
        }
    }



    /**
     * @param classUrl
     */
    open fun packageNameToApk(classUrl: String?, toApkJump: Boolean = false) {
        if (TextUtils.isEmpty(classUrl)) {

            RouterHelper.navigation(RouterHub.ROUTER_BE_OPENED_ACTIVITY)
            return
        }
        try {
            //包名跳转
            val intent = classUrl?.let { packageManager?.getLaunchIntentForPackage(it) }
            if (intent == null) {
                schemeToApk(classUrl, toApkJump)
                return
            }
            startActivity(intent)
        } catch (e: Exception) {
            Log.e("MarketUtils", "其他错误：" + e.message)
            schemeToApk(classUrl, toApkJump)
        }
    }

    /**
     * @param classUrl
     */
    open fun schemeToApk(classUrl: String?, toApkJump: Boolean,busType:Int =0) {
        if (TextUtils.isEmpty(classUrl)) {
            return
        }
        try {
            //深链跳转
            val action = Intent(Intent.ACTION_VIEW)
            action.data = Uri.parse(classUrl)
            startActivity(action)
        } catch (anf: ActivityNotFoundException) {
            Log.e("MarketUtils", "要跳转的应用市场不存在!")
            if (toApkJump) {
                val bundle = Bundle()
                bundle.putInt(
                    "busType",
                    0
                )

//                RouterHelper.navigation(RouterHub.ROUTER_HOME_APK_JUMP)
                RouterHelper.navigationPostcard(RouterHub.ROUTER_HOME_APK_JUMP)
                    .withInt("busType", busType)
                    .navigation(this, object : NavCallback() {
                        override fun onArrival(postcard: Postcard?) {
                        }

                        override fun onLost(postcard: Postcard?) {
                            ToastUtils.showToast(R.string.common_not_page_ac_hint)
                        }
                    })
            } else {
//                startActivity(ComingSoonActivity.class);
                toAcByAction(classUrl)
            }
        }
    }

    fun adSignDataList(mTemp: MutableMap<String, String>? = null): MutableList<String> {
        val dataList: MutableList<String> = mutableListOf()

        val exitTime = System.currentTimeMillis()
        val params = mutableMapOf(
            "timestamp" to exitTime.toString(),
        )
        if (mTemp != null) {
            params.putAll(mTemp)
        }

        val stringA = "${
            params.toSortedMap(compareBy { it })
                .entries.joinToString("&") { "${it.key}=${it.value}" }
        }&accessSecret=e9626eed360d405781c38bf115864c8a"

        dataList.add(exitTime.toString())
        dataList.add(Base64Utils.encode(MD5Utils.md5(stringA, false).toByteArray()))
        return dataList
    }
}